package vip.xiaozhao.intern.baseUtil.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import vip.xiaozhao.intern.baseUtil.intf.entity.VV;
import vip.xiaozhao.intern.baseUtil.intf.mapper.VVMapper;
import vip.xiaozhao.intern.baseUtil.intf.service.VVService;
import vip.xiaozhao.intern.baseUtil.intf.utils.JsonUtils;
import vip.xiaozhao.intern.baseUtil.intf.utils.redis.RedisUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 大V服务实现类
 */
@Service
@Slf4j
public class VVServiceImpl implements VVService {

    // Redis缓存前缀
    private static final String REDIS_VV_COMPANY_POSITION_PREFIX = "vip:company:";
    private static final String REDIS_VV_POSITION_PREFIX = "vip:position:";
    // 缓存过期时间（一天）
    private static final int CACHE_EXPIRE_TIME = RedisUtils.EXRP_ONE_DAY;
    // 默认返回10个大V
    private static final int DEFAULT_VV_COUNT = 10;
    // 大大V数量（前30%）
    private static final int TOP_VV_COUNT = 3;
    // 普通大V数量（后70%）
    private static final int NORMAL_VV_COUNT = 7;

    @Autowired
    private VVMapper vvMapper;

    @Override
    public List<VV> getVVList(Integer companyId, Integer departmentId, Integer positionId) {
        if (companyId == null || positionId == null) {
            log.error("公司ID或职位ID不能为空");
            return Collections.emptyList();
        }

        // 查询符合条件的大V列表
        List<VV> resultList = new ArrayList<>();
        
        // 精确查询条件下的大V列表
        List<VV> directVVs = vvMapper.findByCompanyDepartmentPosition(companyId, departmentId, positionId, null);
        
        // 根据结果数量采取不同策略
        if (directVVs.size() > DEFAULT_VV_COUNT) {
            // 结果 > 10: 按分数划分前30%和后70%
            resultList.addAll(vvMapper.findTopScoreVVs(companyId, departmentId, positionId, TOP_VV_COUNT));
            resultList.addAll(vvMapper.findNormalScoreVVs(companyId, departmentId, positionId, NORMAL_VV_COUNT));
        } else if (directVVs.size() == DEFAULT_VV_COUNT) {
            // 结果 = 10: 直接返回所有结果
            resultList.addAll(directVVs);
        } else {
            // 结果 < 10: 先添加已有结果
            resultList.addAll(directVVs);
            
            // 记录已添加的ID，避免重复
            List<Integer> existIds = resultList.stream().map(VV::getId).collect(Collectors.toList());
            
            // 需要补充的数量
            int needCount = DEFAULT_VV_COUNT - resultList.size();
            
            // 从同公司其他部门相同职位补充
            if (needCount > 0) {
                List<VV> companyVVs = getVVsByCompanyPositionFromCache(companyId, positionId, existIds, needCount);
                if (!CollectionUtils.isEmpty(companyVVs)) {
                    resultList.addAll(companyVVs);
                    existIds.addAll(companyVVs.stream().map(VV::getId).collect(Collectors.toList()));
                    needCount = DEFAULT_VV_COUNT - resultList.size();
                }
            }
            
            // 还不足，从不同公司同职位补充
            if (needCount > 0) {
                List<VV> positionVVs = getVVsByPositionFromCache(positionId, existIds, needCount);
                if (!CollectionUtils.isEmpty(positionVVs)) {
                    resultList.addAll(positionVVs);
                }
            }
        }
        
        return resultList;
    }

    @Override
    public List<VV> getVVsByCompanyPositionFromCache(Integer companyId, Integer positionId, List<Integer> excludeIds, Integer limit) {
        if (companyId == null || positionId == null || limit == null) {
            return Collections.emptyList();
        }
        
        // 构建Redis键
        String redisKey = REDIS_VV_COMPANY_POSITION_PREFIX + companyId + ":position:" + positionId;
        
        // 从Redis获取缓存数据
        List<VV> cachedVVs = RedisUtils.getList(redisKey, VV.class);
        
        if (CollectionUtils.isEmpty(cachedVVs)) {
            // 缓存未命中，从数据库获取并缓存
            cachedVVs = vvMapper.findByCompanyPosition(companyId, positionId, null, 20);
            if (!CollectionUtils.isEmpty(cachedVVs)) {
                RedisUtils.set(redisKey, JsonUtils.toStr(cachedVVs), CACHE_EXPIRE_TIME);
            }
        }
        
        // 过滤掉已存在的ID
        if (!CollectionUtils.isEmpty(cachedVVs) && !CollectionUtils.isEmpty(excludeIds)) {
            cachedVVs = cachedVVs.stream()
                    .filter(vv -> !excludeIds.contains(vv.getId()))
                    .limit(limit)
                    .collect(Collectors.toList());
        }
        
        return cachedVVs != null ? cachedVVs : Collections.emptyList();
    }

    @Override
    public List<VV> getVVsByPositionFromCache(Integer positionId, List<Integer> excludeIds, Integer limit) {
        if (positionId == null || limit == null) {
            return Collections.emptyList();
        }
        
        // 构建Redis键
        String redisKey = REDIS_VV_POSITION_PREFIX + positionId;
        
        // 从Redis获取缓存数据
        List<VV> cachedVVs = RedisUtils.getList(redisKey, VV.class);
        
        if (CollectionUtils.isEmpty(cachedVVs)) {
            // 缓存未命中，从数据库获取并缓存
            cachedVVs = vvMapper.findByPosition(positionId, null, 50);
            if (!CollectionUtils.isEmpty(cachedVVs)) {
                RedisUtils.set(redisKey, JsonUtils.toStr(cachedVVs), CACHE_EXPIRE_TIME);
            }
        }
        
        // 过滤掉已存在的ID
        if (!CollectionUtils.isEmpty(cachedVVs) && !CollectionUtils.isEmpty(excludeIds)) {
            cachedVVs = cachedVVs.stream()
                    .filter(vv -> !excludeIds.contains(vv.getId()))
                    .limit(limit)
                    .collect(Collectors.toList());
        }
        
        return cachedVVs != null ? cachedVVs : Collections.emptyList();
    }

    @Override
    public int updateWeekAnswerStats() {
        // 查询所有大V
        List<VV> allVVs = vvMapper.findAllVVs();
        if (CollectionUtils.isEmpty(allVVs)) {
            return 0;
        }
        
        // 记录更新成功的数量
        int successCount = 0;
        
        // 逐个更新大V的周回答数据
        // 实际场景可能需要通过其他服务获取回答数据
        // 这里简化处理，模拟从其他数据源获取回答数据
        for (VV vv : allVVs) {
            try {
                // 实际项目中应该根据用户ID查询其在过去一周内的回答数据
                // 这里仅为示例，随机生成数据
                int weekAnswered = (int) (Math.random() * 30);
                int weekUnanswered = (int) (Math.random() * 20);
                
                // 更新到数据库
                int result = vvMapper.updateWeekAnswerStats(vv.getId(), weekAnswered, weekUnanswered);
                if (result > 0) {
                    successCount++;
                }
            } catch (Exception e) {
                log.error("更新大V[{}]周回答率失败", vv.getId(), e);
            }
        }
        
        log.info("成功更新{}个大V的周回答率", successCount);
        return successCount;
    }

    @Override
    public boolean updateVVCache() {
        try {
            // 获取所有大V
            List<VV> allVVs = vvMapper.findAllVVs();
            if (CollectionUtils.isEmpty(allVVs)) {
                return false;
            }
            
            // 按公司和职位分组缓存
            allVVs.forEach(vv -> {
                // 同公司同职位缓存
                String companyPositionKey = REDIS_VV_COMPANY_POSITION_PREFIX + vv.getCompanyId() + ":position:" + vv.getPositionId();
                List<VV> companyPositionVVs = vvMapper.findByCompanyPosition(vv.getCompanyId(), vv.getPositionId(), null, 20);
                if (!CollectionUtils.isEmpty(companyPositionVVs)) {
                    RedisUtils.set(companyPositionKey, JsonUtils.toStr(companyPositionVVs), CACHE_EXPIRE_TIME);
                }
                
                // 同职位缓存
                String positionKey = REDIS_VV_POSITION_PREFIX + vv.getPositionId();
                List<VV> positionVVs = vvMapper.findByPosition(vv.getPositionId(), null, 50);
                if (!CollectionUtils.isEmpty(positionVVs)) {
                    RedisUtils.set(positionKey, JsonUtils.toStr(positionVVs), CACHE_EXPIRE_TIME);
                }
            });
            
            log.info("成功更新大V缓存");
            return true;
        } catch (Exception e) {
            log.error("更新大V缓存失败", e);
            return false;
        }
    }
} 